<template>
    <el-auto-resizer>
        <template #default="{ height, width }">
            <el-table-v2 ref="treeTableV2Ref" v-model:expanded-row-keys="expandedRowKeys" :columns="columns"
                :data="treeData" :width="width" :height="height" row-key="infId" :expand-column-key="expandColumnKey"
                :header-height="30" :row-height="tableRowHeight" :row-class="getRowClass" :cache="100">
            </el-table-v2>
        </template>
    </el-auto-resizer>
    <btnDropdownMenu ref="btnDropdownMenuRef" @clickItme="emitFun" />
</template>
  
<script  setup lang="jsx">
import { computed, nextTick, ref, watch } from 'vue'
import textTooltip from '@/lz/base/textTooltip.vue';
import btnDropdownMenu from './btnDropdownMenu.vue'
import { checkPermi } from '@/utils/permission.js'
const { proxy } = getCurrentInstance();
const props = defineProps({
    data: {
        type: Array
    },
    currentTab: {
        type: String,
    },
    isExpandAll: {
        type: Boolean
    },
})
const columns = ref(
    [
        {
            title: "接口名称",
            dataKey: "infName",
            key: "infName",
            width: 350,
            align: "left",
            cellRenderer: ({ rowData }) =>
                <div style="display:flex;align-items: center;flex:1;overflow:hidden;height: 100%;cursor: pointer;" onClick={() => { emitFun('clickRow', rowData) }}>
                    {rowData.infType === 'C' ?
                        (<el-icon style="font-size: 15px; vertical-align: middle;">
                            <FolderOpened />
                        </el-icon >) : ""}
                    <span style="margin-left: 5px;display:flex;align-items: center;overflow:hidden;">
                        {
                            rowData.infType === 'I' ? (
                                <strong style="color: #4CAF77; font-weight: bold;" class="mr5"> {rowData.infMethod}</strong>
                            ) : ""
                        }
                        <textTooltip style="flex:1" content={rowData.infName} />
                    </span>
                </div>
            ,
        },
        {
            title: "操作",
            dataKey: "",
            key: "action",
            width: 50,
            cellRenderer: ({ rowData }) =>

                    (<div onmouseenter={(e) => { mouseOverEvent(e, rowData) }} onmouseleave={(e) => { mouseLevelEvent(e, rowData) }}>
                        <el-button type="primary" plain style="width: 30px" icon={rowData.infType == 'C' ? "Plus" : "MoreFilled"} />
                    </div>) 
        }
    ]
)
const expandColumnKey = ref('infName')
const tableRowHeight = ref(30)

// 是否是第一次加载数据
const isFirst = ref(true);
const treeData = computed(() => {
    flattenData.value = []
    const treeData = setTreeData(proxy.lsh.cloneDeep(props.data))
    if (treeData.length > 0 && isFirst.value) {
        isFirst.value = false;
        if (props.isExpandAll) {
            expandedRowKeys.value = getDataLevel3(treeData, 1);
        }
    }
    return treeData
})
// 获取前三层key
const getDataLevel3 = (list, level) => {
    let result = [];
    list.forEach(item => {
        if (level < 3 && item.children && item.children.length > 0) {
            result.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            result = result.concat(getDataLevel3(item.children, level + 1))
        }
    })
    return result

}

// 处理数据添加id
const flattenData = ref([])
const hasChildRowKey = ref([])
const setTreeData = (list) => {
    return list.map(item => {
        item.id = item.infId;
        flattenData.value.push(item)
        if (item.children && item.children.length > 0) {
            hasChildRowKey.value.push(item.id)
            setTreeData(item.children)
        }
        return item
    })
}
const emit = defineEmits();
const emitFun = (name, data) => {
    emit(name, data)
}
// 添加样式
const currentRowIndex = ref();
const getRowClass = ({ rowIndex, rowData }) => {
    if (rowData.infId == props.currentTab) {
        currentRowIndex.value = rowIndex
        return 'row-current'
    }
    if (rowIndex % 2 !== 0) {
        return 'row-striped'
    }
}

// 展开折叠
const expandedRowKeys = ref([])
const expandTree = (expand) => {
    if (expand) {
        expandedRowKeys.value = proxy.lsh.cloneDeep(hasChildRowKey.value)
    } else {
        expandedRowKeys.value = []
    }
}

// 鼠标进入生成下拉列表
const mouseOverEvent = (event, data) => {
    proxy.$refs.btnDropdownMenuRef.openDropdown(event, data)
}
// 鼠标移出销毁下拉列表
const mouseLevelEvent = (event, data) => {
    proxy.$refs.btnDropdownMenuRef.closeDropdown(event, data)
}

// 拉平展示中的树
const flatShowTree = (tree) => {
    return tree.reduce((list, item) => {
        list.push(item)
        if (item.children && item.children.length > 0 && expandedRowKeys.value.includes(item.id)) {
            return list.concat(flatShowTree(item.children, list))
        }
        return list
    }, [])
}


watch([() => props.currentTab, () => currentRowIndex.value], ([newCurrentTab, newCurrentRow], [oldCurrentTab, oldCurrentRow]) => {
    if (newCurrentRow != oldCurrentRow) {
        nextTick(() => {
            // 滚动模式使用auto,视野范围内的不会再滚动
            proxy.$refs.treeTableV2Ref?.scrollToRow(currentRowIndex.value, 'auto')
        })
        return
    }
    if (newCurrentTab != oldCurrentTab) {
        const currentRow = flattenData.value.filter(item => {
            return item.id == props.currentTab
        })[0]
        if (currentRow && currentRow.ancestors) {
            expandedRowKeys.value = [...new Set([...expandedRowKeys.value, ...currentRow.ancestors.split(',')])]
        }
        // 监听currentTab，补充未渲染时row-class函数不会执行，currentRowIndex不变化
        const currentIndex = flatShowTree(treeData.value).findIndex(item => {
            return item.id == props.currentTab
        })
        if (currentIndex != -1) {
            currentRowIndex.value = currentIndex
        }
    }


})
watch(() => props.isExpandAll, (newExpand, oldExpand) => {
    if (newExpand != oldExpand) {
        expandTree(props.isExpandAll)
        return
    }
}, { immediate: true })

defineExpose({ expandTree })

</script>
<style lang="scss" scoped>
.el-table-v2 {
    font-size: 12px;

    :deep(.el-table-v2__header-cell) {
      color: #000000;
      background-color: #d0e7ff;
    }

    :deep(.el-table-v2__header-row, .el-table-v2__header-cell) {
        background-color: #4949f1
    }

    :deep(.row-striped) {
        background: var(--el-fill-color-lighter);
    }

    :deep(.row-current) {
        background-color: var(--el-table-current-row-bg-color);
    }
}
</style>

